<template>
  <div class="content">
    <div class="scroll-view-box">
      <projectMsg :projectId="project_id" :hrefProject="true" type="setting"></projectMsg>
      <el-form :model="cjjsdRuleForm" :rules="cjjsdRules" ref="cjjsdRuleForm" label-position="top" label-width="120px"
        inline>
        <div class="user-title-box">合同金额</div>
        <el-form-item label="合同金额" prop="contract_price">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.contract_price"
            v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="报价金额 " prop="quotation_amount">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.quotation_amount"
            v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="签约优惠金额" prop="discount_amount">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.discount_amount"
            v-input-limit="2"></el-input>
        </el-form-item>
        <div class="user-title-box">增减项金额</div>
        <el-form-item label="增减项金额" prop="changes_amount">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.changes_amount"
            v-input-limit="2"></el-input>
        </el-form-item>
        <div class="user-title-box">成本金额</div>
        <el-form-item label="成本总金额" prop="settlement_cost_amount">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.settlement_cost_amount"
            v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="现场采购成本" prop="procurement_cost">
          <el-input v-input-limit="2" @input="inputFunc" class="input-width" clearable
            v-model="cjjsdRuleForm.procurement_cost"></el-input>
        </el-form-item>
        <el-form-item label="公司集采成本" prop="centralized_procurement_cost">
          <el-input v-input-limit="2" @input="inputFunc" class="input-width" clearable
            v-model="cjjsdRuleForm.centralized_procurement_cost"></el-input>
        </el-form-item>
        <el-form-item label="管理成本" prop="management_costs">
          <el-input @input="inputFunc" class="input-width" clearable v-model="cjjsdRuleForm.management_costs"
            v-input-limit="2"></el-input>
        </el-form-item>
        <div class="user-title-box">总计</div>
        <el-form-item label="应结算金额" prop="settlement_amount">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.settlement_amount"
            v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="利润金额" prop="profit_amount">
          <el-input v-input-limit="2" disabled class="input-width" clearable
            v-model="cjjsdRuleForm.profit_amount"></el-input>
        </el-form-item>
        <el-form-item label="结算利润率" prop="settlement_profit_margin">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.settlement_profit_margin"
            v-input-limit="2">
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
        <div class="user-title-box">收款情况</div>
        <el-form-item label="已收款">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.paid_amount" v-input-limit="2">
          </el-input>
        </el-form-item>
        <el-form-item label="未收款">
          <el-input disabled class="input-width" clearable v-model="cjjsdRuleForm.unpaid_amount" v-input-limit="2">
          </el-input>
        </el-form-item>
        <div class="user-title-box">附件</div>
        <el-form-item class="input-width" label="结算单 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="settlement_file">
          <div class="file-list-box">
            <div class="file-item-box" v-for="(item, index) in cjjsdRuleForm.settlement_file" :key="index">
              <div class="el-icon-delete-box" @click="cjjsdFileRemove(index, 'settlement_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" />
              </el-tooltip>
            </div>
            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#"
              :show-file-list="false" :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                cjjsdChangeFile(file, fileList, 'settlement_file');
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item class="input-width" label="结算利润单 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="inventory_file">
          <div class="file-list-box">
            <div class="file-item-box" v-for="(item, index) in cjjsdRuleForm.inventory_file" :key="index">
              <div class="el-icon-delete-box" @click="cjjsdFileRemove(index, 'inventory_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" />
              </el-tooltip>
            </div>

            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#"
              :show-file-list="false" :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                cjjsdChangeFile(file, fileList, 'inventory_file');
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item class="input-width" label="结算成本单 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="profit_statement_file">
          <div class="file-list-box">
            <div class="file-item-box" v-for="(item, index) in cjjsdRuleForm.profit_statement_file" :key="index">
              <div class="el-icon-delete-box" @click="cjjsdFileRemove(index, 'profit_statement_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" />
              </el-tooltip>
            </div>

            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#"
              :show-file-list="false" :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                cjjsdChangeFile(file, fileList, 'profit_statement_file');
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :rows="4" class="input-width" v-model="cjjsdRuleForm.remark" type="textarea"></el-input>
        </el-form-item>
        <template v-if="cjjsdRuleForm.hisFile">
          <div class="user-title-box">历史附件</div>
          <el-form-item class="input-width" label="结算单" prop="settlement_file">
            <div class="file-list-box">
              <div class="file-item-box" v-for="(item, index) in cjjsdRuleForm.hisFile.settlement_file" :key="index">
                <el-tooltip class="item" effect="dark" :content="item.file_name" placement="top">
                  <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
          <el-form-item class="input-width" label="结算利润单" prop="inventory_file">
            <div class="file-list-box">
              <div class="file-item-box" v-for="(item, index) in cjjsdRuleForm.hisFile.inventory_file" :key="index">
                <el-tooltip class="item" effect="dark" :content="item.file_name" placement="top">
                  <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
          <el-form-item class="input-width" label="结算成本单" prop="profit_statement_file">
            <div class="file-list-box">
              <div class="file-item-box" v-for="(item, index) in cjjsdRuleForm.hisFile.profit_statement_file"
                :key="index">
                <el-tooltip class="item" effect="dark" :content="item.file_name" placement="top">
                  <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" clearable @click="cjjsdSubmit('cjjsdRuleForm')" :disabled="diaLoading"
          :loading="diaLoading">提交</el-button>
        <el-button @click="cjjsdCancel('cjjsdRuleForm')">关闭</el-button>
      </span>
    </div>
  </div>
</template>
<script>
import common from "@/api/common";
import projectApi from "@/api/projectApi";
import * as math from "mathjs";
import projectMsg from "@/components/ProjectMsg";

export default {
  name: "addSettlemen",
  components: {
    projectMsg,
  },
  data() {
    var file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传文件"));
      } else {
        callback();
      }
    };
    return {
      detailData: {},
      diaLoading: false,
      cjjsdVisible: false,
      cjjsdRuleForm: {
        remark: "",
        settlement_amount: "",
        settlement_cost_amount: "",
        procurement_cost: "",
        centralized_procurement_cost: "",
        management_costs: "",
        profit_amount: "",
        settlement_profit_margin: "",
        settlement_file: [],
        inventory_file: [],
        profit_statement_file: [],
      },
      cjjsdRules: {
        settlement_amount: [
          { required: true, message: "请输入应结算金额", trigger: "change" },
        ],
        settlement_cost_amount: [
          { required: true, message: "请输入成本金额", trigger: "change" },
        ],
        procurement_cost: [
          { required: true, message: "请输入现场采购成本", trigger: "change" },
        ],
        centralized_procurement_cost: [
          { required: true, message: "请输入公司集采成本", trigger: "change" },
        ],
        management_costs: [
          { required: true, message: "请输入管理成本", trigger: "change" },
        ],
        profit_amount: [
          { required: true, message: "请输入利润金额", trigger: "change" },
        ],
        settlement_profit_margin: [
          { required: true, message: "请输入结算利润率", trigger: "change" },
        ],
        settlement_file: {
          required: true,
          validator: file,
          trigger: "change",
        },
        inventory_file: {
          required: true,
          validator: file,
          trigger: "change",
        },
        profit_statement_file: {
          required: true,
          validator: file,
          trigger: "change",
        },
      },
      project_id: ""
    };
  },
  watch: {},
  computed: {},
  mounted() {
    this.project_id = this.$route.query.id;
    this.getProjectLog();
  },
  methods: {
    // 获取项目日志
    getProjectLog() {
      this.logList = [];
      projectApi
        .getProjectLogList({
          project_id: this.$route.query.id,
          // log_type: Number(this.activeName),
        })
        .then((res) => {
          console.log(res, "项目日志");
          if (res.code == 200) {
            let hisData = '';
            res.data.forEach((item) => {
              if (item.form_data) {
                item.form_data = JSON.parse(item.form_data);
              }
              // 拿到最近一条历史结算单（重新提交用）
              if (item.log_status == 380 && !hisData) {
                hisData = item.form_data;
                this.cjjsdRuleForm = {
                  remark: hisData.remark,
                  settlement_file: [],
                  inventory_file: [],
                  profit_statement_file: [],
                  hisFile: {
                    settlement_file: hisData.settlement_file,
                    inventory_file: hisData.inventory_file,
                    profit_statement_file: hisData.profit_statement_file,
                  },

                  contract_price: hisData.contract_price,//合同金额
                  quotation_amount: hisData.quotation_amount,//报价金额
                  discount_amount: hisData.discount_amount,//签约优惠金额
                  changes_amount: hisData.changes_amount,//增减项金额
                  settlement_cost_amount: hisData.settlement_cost_amount,//成本总金额
                  management_costs: hisData.management_costs,//管理成本
                  procurement_cost: hisData.procurement_cost,//现场采购成本
                  centralized_procurement_cost: hisData.centralized_procurement_cost,//公司集采成本
                  settlement_amount: hisData.settlement_amount,//应结算金额
                  profit_amount: hisData.profit_amount,//利润金额
                  settlement_profit_margin: hisData.settlement_profit_margin,//结算利润率
                  paid_amount: hisData.paid_amount,//项目已收款
                  unpaid_amount: hisData.unpaid_amount,//项目未收款
                };
                console.log(this.cjjsdRuleForm)
              }
            });
            if (!hisData) {
              this.selectProjectDetails();
            }
          }
        })
        .catch((err) => {
          this.logLoaidng = false;
        });
    },
    // 出具结算单
    cjjsdCancel() {
      this.$goBackTab(this);
    },
    cjjsdSubmit(formName) {
      let cjjsdRuleForm = this.cjjsdRuleForm;
      console.log(cjjsdRuleForm, "出具结算单参数");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.diaLoading = true;
          let formdata = new FormData();
          formdata.append(
            "data",
            JSON.stringify({
              remark: cjjsdRuleForm.remark,
              contract_price: cjjsdRuleForm.contract_price,//合同金额
              quotation_amount: cjjsdRuleForm.quotation_amount,//报价金额
              discount_amount: cjjsdRuleForm.discount_amount,//签约优惠金额
              changes_amount: cjjsdRuleForm.changes_amount,//增减项金额
              settlement_cost_amount: cjjsdRuleForm.settlement_cost_amount,//成本总金额
              management_costs: cjjsdRuleForm.management_costs,//管理成本
              procurement_cost: cjjsdRuleForm.procurement_cost,//现场采购成本
              centralized_procurement_cost: cjjsdRuleForm.centralized_procurement_cost,//公司集采成本
              settlement_amount: cjjsdRuleForm.settlement_amount,//应结算金额
              profit_amount: cjjsdRuleForm.profit_amount,//利润金额
              settlement_profit_margin: cjjsdRuleForm.settlement_profit_margin,//结算利润率
              paid_amount: cjjsdRuleForm.paid_amount,//项目已收款
              unpaid_amount: cjjsdRuleForm.unpaid_amount,//项目未收款
              project_id: this.project_id,//项目id
            })
          );
          cjjsdRuleForm.settlement_file.forEach((item) => {
            formdata.append("settlement_file[]", item.raw);
          });
          cjjsdRuleForm.inventory_file.forEach((item) => {
            formdata.append("inventory_file[]", item.raw);
          });
          cjjsdRuleForm.profit_statement_file.forEach((item) => {
            formdata.append("profit_statement_file[]", item.raw);
          });
          projectApi
            .issueSettlementStatement(formdata)
            .then((res) => {
              console.log(res, "出具结算单");
              this.diaLoading = false;
              if (res.code == 200) {
                this.cjjsdCancel();
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.code == 200 ? "处理成功" : res.message,
              });
            })
            .catch((err) => {
              this.diaLoading = false;
              this.$message({
                type: "warning",
                message: err.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 输入值计算
    inputFunc() {
      let cjjsdRuleForm = this.cjjsdRuleForm;
      console.log(cjjsdRuleForm, "项目数据");
      // management_costs//管理
      // procurement_cost//现场
      // centralized_procurement_cost//公司


      // ****************************成本总金额(管理成本+现场采购成本+公司集采成本)************************************
      if (cjjsdRuleForm.management_costs &&
        cjjsdRuleForm.procurement_cost &&
        cjjsdRuleForm.centralized_procurement_cost
      ) {
        let settlement_cost_amount = 0;
        settlement_cost_amount = math.format(
          math.add(
            math.bignumber(cjjsdRuleForm.management_costs),
            math.bignumber(cjjsdRuleForm.procurement_cost),
            math.bignumber(cjjsdRuleForm.centralized_procurement_cost)
          )
        );
        cjjsdRuleForm.settlement_cost_amount = Number(settlement_cost_amount).toFixed(2);
        console.log(settlement_cost_amount, "成本总金额");
      } else {
        cjjsdRuleForm.settlement_cost_amount = 0;
        console.log("成本总金额0");
      }
      // ****************************成本金额************************************

      //  *********利润金额==应结算-成本总金额（成本总金额=现场采购成本+公司集采成本+管理成本）***********
      if (cjjsdRuleForm.settlement_amount &&
        cjjsdRuleForm.management_costs &&
        cjjsdRuleForm.procurement_cost &&
        cjjsdRuleForm.centralized_procurement_cost
      ) {
        let profit_amount = 0;
        let profitNum = Number(math.format(
          math.add(
            math.bignumber(cjjsdRuleForm.management_costs),
            math.bignumber(cjjsdRuleForm.procurement_cost),
            math.bignumber(cjjsdRuleForm.centralized_procurement_cost),
          )
        ));
        profit_amount = math.format(
          math.subtract(
            math.bignumber(cjjsdRuleForm.settlement_amount),
            math.bignumber(profitNum)
          )
        );
        cjjsdRuleForm.profit_amount = Number(profit_amount).toFixed(2);
        console.log(profit_amount, "利润金额");
      } else {
        cjjsdRuleForm.profit_amount = 0;
        console.log("利润金额0");
      }
      //  ****************************利润金额************************************

      //  ****************************利润率(应结算-成本)/成本*100************************************
      if (cjjsdRuleForm.settlement_amount && cjjsdRuleForm.settlement_cost_amount) {
        let settlement_profit_margin = 0;
        let settlementNum = Number(math.format(
          math.subtract(
            math.bignumber(cjjsdRuleForm.settlement_amount),
            math.bignumber(cjjsdRuleForm.settlement_cost_amount)
          )
        ));
        settlement_profit_margin = math.format(
          math.divide(
            math.bignumber(settlementNum),
            math.bignumber(cjjsdRuleForm.settlement_cost_amount)
          )
        );
        cjjsdRuleForm.settlement_profit_margin = Number(settlement_profit_margin * 100).toFixed(2);
        console.log(settlement_profit_margin, "利润率")
      } else {
        cjjsdRuleForm.settlement_profit_margin = 0;
        console.log("利润率0")
      }
      //  ****************************利润率************************************
      this.cjjsdRuleForm = cjjsdRuleForm;
    },
    //文件
    cjjsdChangeFile(file, list, type) {
      console.log(file, list, type);
      let cjjsdRuleForm = this.cjjsdRuleForm;
      cjjsdRuleForm[type] = [file];
      this.cjjsdRuleForm;
    },
    cjjsdFileRemove(index, type) {
      console.log(index, type);
      let cjjsdRuleForm = this.cjjsdRuleForm;
      cjjsdRuleForm[type].splice(index, 1);
      this.cjjsdRuleForm = cjjsdRuleForm;
    },
    // 详情
    selectProjectDetails() {
      return new Promise((resolve, reject) => {
        common
          .selectProjectDetails({
            project_id: this.$route.query.id,
          })
          .then((res) => {
            console.log(res, "项目详情", res.data.status, res.data.id);
            if (res.code == 200) {
              this.cjjsdRuleForm.contract_price = res.data.contract_price;//合同金额
              this.cjjsdRuleForm.quotation_amount = Number(res.data.contract_price) + Number(res.data.discount_amount);//报价金额（合同金额+优惠金额）
              this.cjjsdRuleForm.discount_amount = res.data.discount_amount;//签约优惠金额
              this.cjjsdRuleForm.changes_amount = res.data.change_total;//增减项总额
              this.cjjsdRuleForm.paid_amount = res.data.paid_amount;
              this.cjjsdRuleForm.unpaid_amount = res.data.unpaid_amount;


              this.cjjsdRuleForm.settlement_amount = Number(math.format(
                math.add(
                  math.bignumber(res.data.contract_price),
                  math.bignumber(res.data.change_total),
                )
              )).toFixed(2);//应结算金额（施工签约金额+增减项总额）

              this.detailData = res.data;
              console.log(this.cjjsdRuleForm, "this.cjjsdRuleForm")
            } else {
              this.$message.warning(res.message);
            }
          })
          .catch((err) => {
            this.$message.warning(err.message);
          });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/addPage.scss";
</style>